package com.cpe.repository.config;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@PropertySource({ "classpath:jdbc.properties", "classpath:mybatis.properties" })
public class MyBatisConfig {

	@Resource
	private Environment environment;

	@Bean
	public DataSource dataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(environment.getProperty("jdbc.driverClassName"));
		dataSource.setUrl(environment.getProperty("jdbc.url"));
		dataSource.setUsername(environment.getProperty("jdbc.usr"));
		dataSource.setPassword(environment.getProperty("jdbc.pwd"));
		dataSource.setInitialSize(Integer.parseInt(environment.getProperty("dbcp.initialSize")));
		dataSource.setMaxTotal(Integer.parseInt(environment.getProperty("dbcp.maxTotal")));
		return dataSource;
	}

	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource());

		String configLocation = environment.getProperty("mybatis.configLocation");
		sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(configLocation));

		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		String mapperLocations = environment.getProperty("mybatis.mapperLocations");
		sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));

		String typeAliasesPackage = environment.getProperty("mybatis.typeAliasesPackage");
		sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);

		return sqlSessionFactoryBean.getObject();
	}

	@Bean
	public PlatformTransactionManager txManager() {
		return new DataSourceTransactionManager(dataSource());
	}

}
